package com.cq.hd.product.factory;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cq.hd.common.constant.Constant;
import com.cq.hd.common.enums.biz.*;
import com.cq.hd.common.response.Throw;
import com.cq.hd.common.utils.BeanUtils;
import com.cq.hd.common.utils.LocalDateUtil;
import com.cq.hd.common.utils.NoUtils;
import com.cq.hd.member.api.TbBusinessApi;
import com.cq.hd.member.api.dto.UpdateActiveCountDto;
import com.cq.hd.member.api.vo.BusinessVo;
import com.cq.hd.product.api.dto.*;
import com.cq.hd.product.mapper.*;
import com.cq.hd.product.po.*;
import com.cq.hd.product.service.TbActiveLabelService;
import com.cq.hd.product.validator.ActivePublishValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
public class GroupActiveReleaseHandler extends AbstractActiveReleaseHandler {

    @Autowired
    private TbGoodsMapper goodsMapper;

    @Autowired
    private TbActiveGoodsStockMapper activeGoodsStockMapper;

    @Autowired
    private TbActiveGoodsSubsidyMapper activeGoodsSubsidyMapper;

    @Autowired
    private TbActiveGoodsMapper activeGoodsMapper;

    @Autowired
    private TbActiveDiscountMapper activeDiscountMapper;

    @Autowired
    private TbActiveAgentMapper activeAgentMapper;

    @Autowired
    private TbActiveRedPacketMapper activeRedPacketMapper;

    @Autowired
    private TbActiveMapper activeMapper;

    @Autowired
    private TbBusinessApi businessApi;

    @Autowired
    private TbActiveLabelService activeLabelService;

    @Autowired
    private PlatformTransactionManager transactionManager;

    @Value("${spring.profiles.active}")
    private String env;

    @Override
    protected Integer getType() {
        return ActiveTypeEnum.GROUP.getValue();
    }

    @Override
    public Long saveActiveData(ActiveReleaseDto activeReleaseDto) {
        // 表单校验
        ActivePublishValidator.validate(activeReleaseDto);
        // 团购活动，是否需要审核 = 否
        activeReleaseDto.setAuditRequired(0);
        // 活动类型(1-团购活动，2-报名活动，3-外部活动)
        String activeTitle = activeReleaseDto.getActiveTitle();
        String activeImg = activeReleaseDto.getActiveImg();
        List<ActiveContent> activeContents = activeReleaseDto.getActiveContents();
        BigDecimal activePrice = activeReleaseDto.getActivePrice();
        BigDecimal originPrice = activeReleaseDto.getOriginPrice();
        Integer totalStock = activeReleaseDto.getTotalStock();
        // 是否是所有经纪人可推广：1-否，2-是
        Integer agentNumState = activeReleaseDto.getAgentNumState();
        List<Long> agentIds = activeReleaseDto.getAgentIds();
        // 活动状态（1-仅保存，2-去发布）
        Integer activeState = activeReleaseDto.getActiveState();
        // 是否是零元购活动（1-不是，2-是）
        Integer zeroState = activeReleaseDto.getZeroState();

        if (zeroState == null || ZeroStateEnum.typeOf(zeroState) == null) {
            Throw.isBusinessException("请选择零元购状态");
        }

        if (activeState == null || (activeState != 1 && activeState != 2)) {
            Throw.isBusinessException("活动状态值错误");
        }

        if (StringUtils.isEmpty(activeTitle)) {
            Throw.isBusinessException("请输入活动标题");
        }

        if (StringUtils.isEmpty(activeImg)) {
            Throw.isBusinessException("请上传活动图片");
        }

        if (CollectionUtils.isEmpty(activeContents)) {
            Throw.isBusinessException("请输入活动内容");
        } else {
            for (ActiveContent activeContent : activeContents) {
                String content = activeContent.getContent();
                if (StringUtils.isEmpty(content)) {
                    Throw.isBusinessException("请输入活动内容");
                }
            }
        }

        if (totalStock == null) {
            Throw.isBusinessException("请填写活动库存");
        }

        if (totalStock <= 0) {
            Throw.isBusinessException("活动库存必须大于0");
        }

        if (totalStock > 99999999) {
            Throw.isBusinessException("活动库存不能超过99999999");
        }

        if (ZeroStateEnum.NO.getValue().equals(zeroState)) {
            if (activePrice == null || activePrice.compareTo(new BigDecimal("0.1")) < 0) {
                Throw.isBusinessException("活动价格不能少于0.1元");
            }
        } else {
            activePrice = BigDecimal.ZERO;
        }

        if (originPrice != null && originPrice.compareTo(BigDecimal.ZERO) > 0) {
            if (originPrice.compareTo(new BigDecimal("99999999")) > 0) {
                Throw.isBusinessException("划线价格必须小于99999999元");
            }

            if (originPrice.compareTo(activePrice) < 0) {
                Throw.isBusinessException("划线价格必须大于等于活动价格");
            }
        }

        // 校验活动时间
        String startTime = activeReleaseDto.getStartTime();
        String endTime = activeReleaseDto.getEndTime();
        String validStartTime = activeReleaseDto.getValidStartTime();
        String validEndTime = activeReleaseDto.getValidEndTime();

        if (StringUtils.isEmpty(startTime) || StringUtils.isEmpty(endTime)) {
            Throw.isBusinessException("请设置活动时间");
        }

        LocalDateTime startLocalDateTime = null;
        LocalDateTime endLocalDateTime = null;
        try {
            startLocalDateTime = LocalDateUtil.toLocalDateTime(startTime, Constant.YYYY_MM_DD_HH_MM_SS);
            endLocalDateTime = LocalDateUtil.toLocalDateTime(endTime, Constant.YYYY_MM_DD_HH_MM_SS);
        } catch (Exception e) {
            Throw.isBusinessException("活动时间设置有误");
        }

        LocalDateTime nowLocalDateTime = LocalDateUtil.getNowLocalDateTime();

        // 活动开始时间，不能早于当前时间
        if (nowLocalDateTime.compareTo(startLocalDateTime) >= 0) {
            Throw.isBusinessException("活动开始时间不能早于当前时间");
        }

        // 活动开始时间，不能大于活动结束时间
        if (startLocalDateTime.compareTo(endLocalDateTime) >= 0) {
            Throw.isBusinessException("活动开始时间不能晚于活动结束时间");
        }

        if (StringUtils.isEmpty(validStartTime) || StringUtils.isEmpty(validEndTime)) {
            Throw.isBusinessException("请设置使用时间");
        }

        LocalDateTime validStartLocalDateTime = null;
        LocalDateTime validEndLocalDateTime = null;
        try {
            validStartLocalDateTime = LocalDateUtil.toLocalDateTime(validStartTime, Constant.YYYY_MM_DD_HH_MM_SS);
            validEndLocalDateTime = LocalDateUtil.toLocalDateTime(validEndTime, Constant.YYYY_MM_DD_HH_MM_SS);
        } catch (Exception e) {
            Throw.isBusinessException("使用时间设置有误");
        }

        // 活动有效开始时间不能晚于活动有效结束时间
        if (validStartLocalDateTime.compareTo(validEndLocalDateTime) >= 0) {
            Throw.isBusinessException("活动有效开始时间不能晚于活动有效结束时间");
        }

        // 有效开始时间不能比活动开始时间早
        if (validStartLocalDateTime.compareTo(startLocalDateTime) < 0) {
            Throw.isBusinessException("活动有效开始时间不能比活动开始时间早");
        }

        // 有效结束时间不能比活动结束时间早
        if (validEndLocalDateTime.compareTo(endLocalDateTime) < 0) {
            Throw.isBusinessException("活动有效结束时间不能比活动结束时间早");
        }

        // 活动时间不能超过360天
        long seconds = LocalDateUtil.getDurationToLocalDateTime(validStartLocalDateTime, validEndLocalDateTime).getSeconds();
        if (seconds > 0) {
            long days = (seconds % 60 % 60 % 24) > 0 ? (seconds / 60 / 60 / 24) + 1 : (seconds / 60 / 60 / 24);
            if (days > 360) {
                Throw.isBusinessException("活动时间不能超过360天");
            }
        }

        // 使用时间不能超过360天
        seconds = LocalDateUtil.getDurationToLocalDateTime(startLocalDateTime, endLocalDateTime).getSeconds();
        if (seconds > 0) {
            long days = (seconds % 60 % 60 % 24) > 0 ? (seconds / 60 / 60 / 24) + 1 : (seconds / 60 / 60 / 24);
            if (days > 360) {
                Throw.isBusinessException("使用时间不能超过360天");
            }
        }

        // 校验活动商品列表
        List<ActiveGoodsSonDto> activeGoods = activeReleaseDto.getActiveGoods();
        if (CollectionUtils.isEmpty(activeGoods)) {
            Throw.isBusinessException("请选择活动商品");
        }

        // 校验补贴设置
        // 补贴设置(0-未设置,1-自动按比例分摊,2-手动设置)
        Integer subsidyState = activeReleaseDto.getSubsidyState();
        if (subsidyState == null || SubsidyStateEnum.typeOf(subsidyState) == null) {
            Throw.isBusinessException("请选择补贴设置");
        }

        // 零元购活动补贴必须走自动按比例分摊，不能手动设置
        if (ZeroStateEnum.YES.getValue().equals(zeroState)) {
            subsidyState = SubsidyStateEnum.AUTO.getValue();
        }

        // 校验多件多折
        // 多件多折状态(1-关闭，2-开启)
        Integer discountState = activeReleaseDto.getDiscountState();
        if (discountState == null || DiscountStateEnum.typeOf(discountState) == null) {
            Throw.isBusinessException("请选择多件多折开启状态");
        }

        List<ActiveDiscountSonDto> activeDiscount = activeReleaseDto.getActiveDiscount();
        if (DiscountStateEnum.OPEN.getValue().equals(discountState)) {
            if (ZeroStateEnum.YES.getValue().equals(zeroState)) {
                Throw.isBusinessException("零元购活动不能开启多件多折");
            }

            if (activePrice.compareTo(new BigDecimal("1")) < 0) {
                Throw.isBusinessException("活动价小于1元,不能开启多件多折");
            }

            if (CollectionUtils.isEmpty(activeDiscount)) {
                Throw.isBusinessException("请设置多件多折");
            }

            for (ActiveDiscountSonDto activeDiscountSonDto : activeDiscount) {
                Integer num = activeDiscountSonDto.getNum();
                if (num <= 0) {
                    Throw.isBusinessException("多件多折的件数必须大于0");
                }
                // 多件多折的打折限制在0.1-10之间
                BigDecimal discount = activeDiscountSonDto.getDiscount();
                if (discount.compareTo(new BigDecimal("0.1")) <= 0 || discount.compareTo(new BigDecimal("10")) >= 0) {
                    Throw.isBusinessException("多件多折的折扣限制在0.1~10之间");
                }
            }
        }

        // 校验分销
        // 分销开启状态(1-关闭，2-开启)
        Integer agentState = activeReleaseDto.getAgentState();
        if (agentState == null || AgentStateEnum.typeOf(agentState) == null) {
            Throw.isBusinessException("请选择分销开启状态");
        }

        // 实际全核销佣金金额=活动价格*佣金比例=固定佣金金额
        BigDecimal actualCommissionAmt = BigDecimal.ZERO;
        if (AgentStateEnum.OPEN.getValue().equals(agentState)) {
            BigDecimal commissionAmt = activeReleaseDto.getCommissionAmt();
            BigDecimal commissionRate = activeReleaseDto.getCommissionRate();
            // 默认佣金类型：0-无，1-佣金，2-佣金比例
            Integer defaultCommissionType = activeReleaseDto.getDefaultCommissionType();
            String otherEquity = activeReleaseDto.getOtherEquity();

            if (defaultCommissionType == null || DefaultCommissionTypeEnum.typeOf(defaultCommissionType) == null) {
                Throw.isBusinessException("请设置默认佣金类型");
            }

            if (ZeroStateEnum.YES.getValue().equals(zeroState) && !DefaultCommissionTypeEnum.NULL.getValue().equals(defaultCommissionType)) {
                Throw.isBusinessException("零元购活动不能设置佣金");
            }

//            if (activePrice.compareTo(new BigDecimal("1")) < 0) {
//                Throw.isBusinessException("0元活动不支持设置佣金");
//            }

            if (DefaultCommissionTypeEnum.NULL.getValue().equals(defaultCommissionType)) {
//                if (StringUtils.isEmpty(otherEquity)) {
//                    Throw.isBusinessException("请设置其他权益");
//                }
            } else if (DefaultCommissionTypeEnum.COMMISSION.getValue().equals(defaultCommissionType)) {
                if (commissionAmt == null || commissionAmt.compareTo(BigDecimal.ZERO) <= 0) {
                    Throw.isBusinessException("请设置佣金");
                }

                // 固定佣金不能大于等于活动价格
                if (commissionAmt.compareTo(activePrice) >= 0) {
                    Throw.isBusinessException("固定金额不能大于等于活动价格");
                }

                // 实际全核销佣金金额=固定佣金
                actualCommissionAmt = activeReleaseDto.getCommissionAmt();
            } else if (DefaultCommissionTypeEnum.COMMISSION_RATE.getValue().equals(defaultCommissionType)) {
                if (commissionRate == null || commissionRate.compareTo(BigDecimal.ZERO) <= 0) {
                    Throw.isBusinessException("请设置佣金比例");
                }

                // 实际全核销佣金金额=活动价格*固定佣金比例
                actualCommissionAmt = activePrice.multiply(activeReleaseDto.getCommissionRate()).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_DOWN);
            }

            if (agentNumState == null || AgentNumStateEnum.typeOf(agentNumState) == null) {
                Throw.isBusinessException("设置推广经纪人类型值错误");
            }

            if (AgentNumStateEnum.NO.getValue().equals(agentNumState) && CollectionUtils.isEmpty(agentIds)) {
                Throw.isBusinessException("请选择推广的经纪人");
            }
        }

        // 红包总金额=红包金额*红包数量
        BigDecimal redPacketTotalAmt = BigDecimal.ZERO;
        BigDecimal firstRedPacketAmt = BigDecimal.ZERO;
        ActiveRedPacketSonDto activeRedPacket = activeReleaseDto.getActiveRedPacket();
        if (activeRedPacket != null) {
            if (ZeroStateEnum.YES.getValue().equals(zeroState)) {
                Throw.isBusinessException("0元购活动不能设置红包");
            }

            if (activePrice.compareTo(new BigDecimal("1")) < 0) {
                Throw.isBusinessException("活动价小于1元,不能设置红包");
            }

            firstRedPacketAmt = activeRedPacket.getFirstRedPacketAmt();
            if (firstRedPacketAmt == null || firstRedPacketAmt.compareTo(BigDecimal.ZERO) <= 0) {
                Throw.isBusinessException("红包金额必须大于0元");
            }

            if (firstRedPacketAmt.compareTo(new BigDecimal("99999999")) > 0) {
                Throw.isBusinessException("红包金额不能大于99999999元");
            }

            Integer redPacketNum = activeRedPacket.getRedPacketNum();
            if (redPacketNum <= 0) {
                Throw.isBusinessException("红包数量必须大于0个");
            }

            if (redPacketNum > 99999999) {
                Throw.isBusinessException("红包数量不能大于99999999个");
            }

            Integer validDay = activeRedPacket.getValidDay();
            if (validDay <= 0) {
                Throw.isBusinessException("红包有效期必须大于0天");
            }

            if (validDay > 99999999) {
                Throw.isBusinessException("红包有效期不能大于99999999天");
            }

            // 活动价格-红包金额必须大于1元
            BigDecimal tmpAmt = activePrice.subtract(firstRedPacketAmt);
            if (tmpAmt.compareTo(new BigDecimal("0.1")) < 0) {
                Throw.isBusinessException("活动价格-红包金额需大于等于0.1元");
            }

//            redPacketTotalAmt = firstRedPacketAmt.multiply(new BigDecimal(redPacketNum));
        }

        Set<String> merchantIdsSet = new HashSet<>();

        // 商品总数
        int goodsNums = 0;
        // 商品总价
        BigDecimal goodsTotalAmt = BigDecimal.ZERO;
        for (ActiveGoodsSonDto activeGood : activeGoods) {
            BigDecimal goodsPrice = activeGood.getGoodsPrice();
            Integer goodsNum = activeGood.getGoodsNum();

            if (goodsNum == null || goodsNum <= 0) {
                Throw.isBusinessException("活动商品个数有误，请重新设置");
            }

            if (goodsPrice == null || goodsPrice.compareTo(BigDecimal.ZERO) <= 0) {
                activeGood.setGoodsPrice(BigDecimal.ZERO);
//                Throw.isBusinessException("活动商品价格有误，请重新设置");
            }

            BigDecimal price = goodsPrice.multiply(new BigDecimal(String.valueOf(goodsNum)));
            goodsTotalAmt = goodsTotalAmt.add(price);
            goodsNums += goodsNum;
            // 商品id/商户id(如果是多商户通用券，则会存在多个，使用英文逗号分割)
            String goodsId = activeGood.getGoodsId();

            Integer mulState = activeGood.getMulState();
            if (MulStateEnum.YES.getValue().equals(mulState)) {
                if (StringUtils.isEmpty(goodsId)) {
                    log.error("多商户通用券[{}]未设置可用商户", activeGood.getGoodsName());
                    Throw.isBusinessException("多商户通用券[" + activeGood.getGoodsName() + "]未设置可用商户");
                }

                String[] splitGoodsIdArr = goodsId.split(",");
                merchantIdsSet.addAll(Arrays.asList(splitGoodsIdArr));
            } else {
                if (StringUtils.isEmpty(goodsId)) {
                    log.error("活动商品[{}]id为空", activeGood.getGoodsName());
                    Throw.isBusinessException("活动商品[" + activeGood.getGoodsName() + "]数据错误");
                }

                // 校验活动商品是否处于上架中
                TbGoodsPo tbGoodsPo = goodsMapper.selectById(goodsId);
                // 商品状态（1-待发布(草稿箱)，2-已下架(待发售)，3-已上架）
                if (tbGoodsPo == null || tbGoodsPo.getDelState() != 0) {
                    log.error("活动商品[{}]已下架，goodsId：{}", activeGood.getGoodsName(), activeGood.getGoodsId());
                    Throw.isBusinessException("活动商品[" + activeGood.getGoodsName() + "]已下架，请重新添加商品");
                }

                if (!GoodsStateEnum.ON.getValue().equals(tbGoodsPo.getGoodsState())) {
                    log.error("活动商品[{}]已下架，goodsId：{}", activeGood.getGoodsName(), activeGood.getGoodsId());
                    Throw.isBusinessException("活动商品[" + activeGood.getGoodsName() + "]已下架，请重新添加商品");
                }

                merchantIdsSet.add(String.valueOf(activeGood.getMerchantId()));
            }
        }

        // 如果是手动设置补贴，校验补贴金额是否等于商品总价-活动价格
        if (SubsidyStateEnum.MANUAL.getValue().equals(subsidyState)) {
            List<ActiveGoodsSubsidySonDto> activeGoodsSubsidy = activeReleaseDto.getActiveGoodsSubsidy();
            if (CollectionUtils.isEmpty(activeGoodsSubsidy)) {
                Throw.isBusinessException("请设置活动商品的补贴金额");
            }

            // 判断商品补贴列表个数是否与活动商品总个数相同
            if (activeGoodsSubsidy.size() != goodsNums) {
                Throw.isBusinessException("活动商品补贴与活动商品个数不等");
            }

            // 累加填写的补贴金额
            BigDecimal totalSubsidyAmt = BigDecimal.ZERO;
            for (ActiveGoodsSubsidySonDto activeGoodsSubsidySonDto : activeGoodsSubsidy) {
                BigDecimal goodsPrice = activeGoodsSubsidySonDto.getGoodsPrice();
                BigDecimal getSubsidyAmt = activeGoodsSubsidySonDto.getSubsidyAmt();
                if (getSubsidyAmt != null) {
                    // 补贴金额不能大于商品价格
                    if (goodsPrice.compareTo(getSubsidyAmt) < 0) {
                        Throw.isBusinessException("补贴金额不能超过商品价格");
                    }

                    if (getSubsidyAmt.compareTo(BigDecimal.ZERO) > 0) {
                        totalSubsidyAmt = totalSubsidyAmt.add(getSubsidyAmt);
                    }
                }

                Integer mulState = activeGoodsSubsidySonDto.getMulState();
                if (MulStateEnum.YES.getValue().equals(mulState)) {
                    // 商品id/商户id(如果是多商户通用券，则会存在多个，使用英文逗号分割)
                    String goodsId = activeGoodsSubsidySonDto.getGoodsId();
                    if (!StringUtils.isEmpty(goodsId)) {
                        String[] splitGoodsIdArr = goodsId.split(",");
                        merchantIdsSet.addAll(Arrays.asList(splitGoodsIdArr));
                    }
                } else {
                    merchantIdsSet.add(String.valueOf(activeGoodsSubsidySonDto.getMerchantId()));
                }
            }

            // 单订单补贴金额=商品价格总和-活动价+单个红包金额+佣金
            BigDecimal needTotalSubsidyAmt = goodsTotalAmt.subtract(activePrice).add(firstRedPacketAmt).add(actualCommissionAmt);

            // 填写的补贴金额总和（没加佣金和单个红包的）须等于单订单补贴金额
            if (totalSubsidyAmt.compareTo(needTotalSubsidyAmt) != 0) {
                Throw.isBusinessException("补贴金额有误，请重新填写");
            }
        }

        BusinessVo businessVo = businessApi.getActiveCount(activeReleaseDto.getUserId(), activeReleaseDto.getBusinessId()).unpack();
        if (businessVo == null) {
            Throw.isBusinessException("商家不存在");
        }

        if (ActiveStateEnum.NO_START.getValue().equals(activeState)) {
            // 判断商家发布活动次数是否足够
            Integer activeCount = businessVo.getActiveCount();
            if (activeCount < 1) {
                Throw.isBusinessException("发布活动次数不足");
            }
        }

        // 活动仅限x个商户参与
        Integer maxMerchantCount = businessVo.getSingleActiveMerchantCount();
        if (maxMerchantCount != null && maxMerchantCount < merchantIdsSet.size()) {
            log.error("maxMerchantCount: {}, merchantIdsSet: {}", maxMerchantCount, merchantIdsSet);
            Throw.isBusinessException("活动仅限" + maxMerchantCount + "个商户参与");
        }

        TbActivePo tbActivePo = new TbActivePo();
        BeanUtils.copyProperties(activeReleaseDto, tbActivePo);
        tbActivePo.setContent(JSON.toJSONString(activeContents));
        // 活动状态（1-仅保存，2-去发布）
        tbActivePo.setActiveState(ActiveStateEnum.NO_RELEASE.getValue().equals(activeState)
                ? ActiveStateEnum.NO_RELEASE.getValue()
                : ActiveStateEnum.NO_START.getValue());
        tbActivePo.setActiveNo(NoUtils.getActiveNo());
        tbActivePo.setTotalStock(totalStock);
        tbActivePo.setRemainStock(totalStock);
        tbActivePo.setStartTime(startLocalDateTime);
        tbActivePo.setEndTime(endLocalDateTime);
        tbActivePo.setValidStartTime(validStartLocalDateTime);
        tbActivePo.setValidEndTime(validEndLocalDateTime);
        tbActivePo.setFirstRedPacketAmt(activeRedPacket == null ? BigDecimal.ZERO : activeRedPacket.getFirstRedPacketAmt());
        tbActivePo.setCreateTime(nowLocalDateTime);
        // 如果是发布，则记录发布时间
        if (ActiveStateEnum.NO_START.getValue().equals(tbActivePo.getActiveState())) {
            tbActivePo.setReleaseTime(nowLocalDateTime);
        }

        // 处理关联的商户id
        if (CollectionUtils.isEmpty(merchantIdsSet)) {
            tbActivePo.setRelationMerchantIds("0");
        } else {
            // 校验所选择的商户是否与商家绑定
//            List<Long> merchantIds = businessApi.listRelationMerchantId(activeReleaseDto.getUserId(), activeReleaseDto.getBusinessId()).unpack();
//            for (String merchantId : merchantIdsSet) {
//                if (!merchantIds.contains(Long.parseLong(merchantId))) {
//                    Throw.isBusinessException("选择的商品或补贴数据已过期，请重新选择");
//                }
//            }

            tbActivePo.setRelationMerchantIds(String.join(",", merchantIdsSet) + ",");
        }

        return saveGroupActiveData(activeReleaseDto, tbActivePo, nowLocalDateTime);
    }

    private Long saveGroupActiveData(ActiveReleaseDto activeReleaseDto,
                                     TbActivePo tbActivePo,
                                     LocalDateTime nowLocalDateTime) {
        ActiveRedPacketSonDto activeRedPacket = activeReleaseDto.getActiveRedPacket();
        Long activeId = tbActivePo.getId();
        TransactionStatus transaction = transactionManager.getTransaction(new DefaultTransactionAttribute());

        try {
            // 添加活动数据
            int count;
            if (tbActivePo.getId() == null) {
                // 添加活动
                count = activeMapper.insert(tbActivePo);
            } else {
                // 修改活动
                count = activeMapper.updateById(tbActivePo);

                // 删除活动商品关联表
                activeGoodsMapper.delete(new QueryWrapper<TbActiveGoodsPo>().eq("active_id", activeId));

                // 删除活动商品补贴数据
                activeGoodsSubsidyMapper.delete(new QueryWrapper<TbActiveGoodsSubsidyPo>().eq("active_id", activeId));

                // 删除活动折扣关联数据
                activeDiscountMapper.delete(new QueryWrapper<TbActiveDiscountPo>().eq("active_id", activeId));

                // 删除活动经纪人关联数据
                activeAgentMapper.delete(new QueryWrapper<TbActiveAgentPo>().eq("active_id", activeId));

                // 删除活动红包数据
                activeRedPacketMapper.delete(new QueryWrapper<TbActiveRedPacketPo>().eq("active_id", activeId));
            }
            if (count == 0) {
                log.error("添加活动失败，保存活动数据异常");
                Throw.isBusinessException("添加活动失败");
            }
            activeId = tbActivePo.getId();

            // 添加活动标签关联
            List<Long> labelIds = Collections.emptyList();
            if (!CollectionUtils.isEmpty(activeReleaseDto.getLabels())) {
                labelIds = activeReleaseDto.getLabels().stream().map(ActiveLabelDto::getId).collect(Collectors.toList());
            }
            activeLabelService.saveActiveLabels(activeId, labelIds);

            // 校验活动商品库存是否充足
            // 添加活动商品关联数据，添加商品活动库存表，扣减商品库存，增加冻结库存数据
            for (ActiveGoodsSonDto activeGood : activeReleaseDto.getActiveGoods()) {
                Integer goodsNum = activeGood.getGoodsNum();
                Integer mulState = activeGood.getMulState();
                if (mulState == null) {
                    Throw.isBusinessException("活动商品数据异常");
                }

                if (MulStateEnum.NO.getValue().equals(mulState)) {
                    // 如果是发布活动，则扣除商品库存
                    if (ActiveStateEnum.NO_START.getValue().equals(tbActivePo.getActiveState())) {
                        int subTotalStock = goodsNum * tbActivePo.getTotalStock();

                        // 扣除商品的库存
                        count = goodsMapper.subStock(Long.parseLong(activeGood.getGoodsId()), subTotalStock);
                        if (count == 0) {
                            log.error("添加活动失败，扣减商品库存异常");
                            Throw.isBusinessException("商品【" + activeGood.getGoodsName() + "】库存不足");
                        }

                        TbActiveGoodsStockPo tbActiveGoodsStockPo = new TbActiveGoodsStockPo();
                        tbActiveGoodsStockPo.setBusinessId(activeReleaseDto.getBusinessId());
                        tbActiveGoodsStockPo.setMerchantId(activeGood.getMerchantId());
                        tbActiveGoodsStockPo.setActiveId(activeId);
                        tbActiveGoodsStockPo.setGoodsId(Long.parseLong(activeGood.getGoodsId()));
                        tbActiveGoodsStockPo.setFreezeStock(subTotalStock);
                        tbActiveGoodsStockPo.setCreateTime(nowLocalDateTime);
                        count = activeGoodsStockMapper.insert(tbActiveGoodsStockPo);
                        if (count == 0) {
                            log.error("添加活动失败，保存商品活动库存数据异常");
                            Throw.isBusinessException("添加活动失败");
                        }
                    }
                } else {
                    // 将多商户通用券的默认图片设置
                    activeGood.setGoodsImgs(Constant.MUL_MERCHANT_GOODS_IMG_URL);
                }

                TbActiveGoodsPo tbActiveGoodsPo = new TbActiveGoodsPo();
                BeanUtils.copyProperties(activeGood, tbActiveGoodsPo);
                tbActiveGoodsPo.setBusinessId(activeReleaseDto.getBusinessId());
                tbActiveGoodsPo.setActiveId(activeId);
                tbActiveGoodsPo.setCreateTime(nowLocalDateTime);

                if (MulStateEnum.NO.getValue().equals(mulState)) {
                    // 从商品重新获取核销方式和票付通参数（不确定前端是否会传参）
                    TbGoodsPo goodsPo = goodsMapper.selectById(activeGood.getGoodsId());
                    tbActiveGoodsPo.setVerifyType(goodsPo.getVerifyType());
                    tbActiveGoodsPo.setPftSupplier(goodsPo.getPftSupplier());
                    tbActiveGoodsPo.setPftProduct(goodsPo.getPftProduct());
                    tbActiveGoodsPo.setPftTicket(goodsPo.getPftTicket());
                }

                count = activeGoodsMapper.insert(tbActiveGoodsPo);
                if (count == 0) {
                    log.error("添加活动失败，保存活动商品关联数据异常");
                    Throw.isBusinessException("添加活动失败");
                }
            }

            // 添加活动商品补贴数据
            if (SubsidyStateEnum.MANUAL.getValue().equals(activeReleaseDto.getSubsidyState()) && !CollectionUtils.isEmpty(activeReleaseDto.getActiveGoodsSubsidy())) {
                for (ActiveGoodsSubsidySonDto activeGoodsSubsidySonDto : activeReleaseDto.getActiveGoodsSubsidy()) {
                    TbActiveGoodsSubsidyPo tbActiveGoodsSubsidyPo = new TbActiveGoodsSubsidyPo();
                    BeanUtils.copyProperties(activeGoodsSubsidySonDto, tbActiveGoodsSubsidyPo);
                    tbActiveGoodsSubsidyPo.setBusinessId(activeReleaseDto.getBusinessId());
                    tbActiveGoodsSubsidyPo.setActiveId(activeId);
                    tbActiveGoodsSubsidyPo.setGoodsId(activeGoodsSubsidySonDto.getGoodsId());
                    tbActiveGoodsSubsidyPo.setCreateTime(nowLocalDateTime);

                    count = activeGoodsSubsidyMapper.insert(tbActiveGoodsSubsidyPo);
                    if (count == 0) {
                        log.error("添加活动失败，保存活动商品补贴数据异常");
                        Throw.isBusinessException("添加活动失败");
                    }
                }
            }

            // 添加活动折扣关联数据
            if (DiscountStateEnum.OPEN.getValue().equals(activeReleaseDto.getDiscountState()) && !CollectionUtils.isEmpty(activeReleaseDto.getActiveDiscount())) {
                for (ActiveDiscountSonDto activeDiscountSonDto : activeReleaseDto.getActiveDiscount()) {
                    TbActiveDiscountPo tbActiveDiscountPo = new TbActiveDiscountPo();
                    tbActiveDiscountPo.setBusinessId(activeReleaseDto.getBusinessId());
                    tbActiveDiscountPo.setActiveId(activeId);
                    tbActiveDiscountPo.setNum(activeDiscountSonDto.getNum());
                    tbActiveDiscountPo.setDiscount(activeDiscountSonDto.getDiscount());
                    tbActiveDiscountPo.setCreateTime(nowLocalDateTime);

                    count = activeDiscountMapper.insert(tbActiveDiscountPo);
                    if (count == 0) {
                        log.error("添加活动失败，保存活动折扣关联数据异常");
                        Throw.isBusinessException("添加活动失败");
                    }
                }
            }

            // 添加活动经纪人关联数据
            if (AgentNumStateEnum.NO.getValue().equals(activeReleaseDto.getAgentNumState()) && !CollectionUtils.isEmpty(activeReleaseDto.getAgentIds())) {
                for (Long agentId : activeReleaseDto.getAgentIds()) {
                    TbActiveAgentPo tbActiveAgentPo = new TbActiveAgentPo();
                    tbActiveAgentPo.setBusinessId(activeReleaseDto.getBusinessId());
                    tbActiveAgentPo.setActiveId(activeId);
                    tbActiveAgentPo.setAgentId(agentId);
                    tbActiveAgentPo.setCreateTime(nowLocalDateTime);

                    count = activeAgentMapper.insert(tbActiveAgentPo);
                    if (count == 0) {
                        log.error("添加活动失败，保存活动经纪人关联数据异常");
                        Throw.isBusinessException("添加活动失败");
                    }
                }
            }

            // 添加活动红包数据
            if (activeRedPacket != null) {
                TbActiveRedPacketPo tbActiveRedPacketPo = new TbActiveRedPacketPo();
                tbActiveRedPacketPo.setBusinessId(activeReleaseDto.getBusinessId());
                tbActiveRedPacketPo.setActiveId(activeId);
                tbActiveRedPacketPo.setTitle("新人首单优惠");
                tbActiveRedPacketPo.setAmt(activeRedPacket.getFirstRedPacketAmt());
                tbActiveRedPacketPo.setActiveTitle(activeReleaseDto.getActiveTitle());
                tbActiveRedPacketPo.setTotalNum(activeRedPacket.getRedPacketNum());
                tbActiveRedPacketPo.setRemainNum(activeRedPacket.getRedPacketNum());
                tbActiveRedPacketPo.setValidDay(activeRedPacket.getValidDay());
                tbActiveRedPacketPo.setCreateTime(nowLocalDateTime);

                count = activeRedPacketMapper.insert(tbActiveRedPacketPo);
                if (count == 0) {
                    log.error("添加活动失败，保存活动红包数据异常");
                    Throw.isBusinessException("添加活动失败");
                }
            }

            // 营销活动 - 拼团
            if (PromotionTypeEnum.GROUP_BUY.name().equals(activeReleaseDto.getPromotionType())) {
                activeReleaseDto.setId(tbActivePo.getId());
                activeGroupBuyService.saveGroupBuyActive((GroupBuyActiveReleaseDto) activeReleaseDto);
            }

            // 如果是发布活动，则扣除商家活动次数，并记录活动次数流水
            if (ActiveStateEnum.NO_START.getValue().equals(tbActivePo.getActiveState())) {
                UpdateActiveCountDto updateActiveCountDto = new UpdateActiveCountDto();
                updateActiveCountDto.setBusinessId(activeReleaseDto.getBusinessId());
                updateActiveCountDto.setUserId(activeReleaseDto.getUserId());
                updateActiveCountDto.setRelationId(activeId);
                updateActiveCountDto.setTradeActiveCount(1);
                updateActiveCountDto.setTradeType(ActiveCountTradeTypeEnum.RELEASE_ACTIVE.getValue());
                updateActiveCountDto.setTradeTime(nowLocalDateTime);
                Boolean updateState = businessApi.subActiveCount(updateActiveCountDto).unpack();
                if (!updateState) {
                    log.error("添加活动失败，扣除发布活动个数异常");
                    Throw.isBusinessException("发布活动次数不足");
                }
            }

            transactionManager.commit(transaction);
        } catch (Exception e) {
            //回滚事务
            transactionManager.rollback(transaction);
            log.error("<添加团购活动>事务异常回滚", e);
            Throw.isBusinessException(e.getMessage());
        }

        return activeId;
    }


}
